/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sft.Autenticacao.Login.GUI;

import java.awt.HeadlessException;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import sft.Autenticacao.Login.Logica.Login;
import sft.Autenticacao.Login.LoginControle;
import sft.Autenticacao.perfil.PerfilControle;
import sft.Autenticacao.perfil.logica.PerfilAcesso;
import sft.Principal.Principal;

public class JICad_Login extends javax.swing.JInternalFrame {

    /**
     * Creates new form JICad_Login
     */
    private static Principal t;

    public JICad_Login(Principal p) {
        t = p;
        initComponents();
        iniciarComponentes();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollTabela = new javax.swing.JScrollPane();
        jTTabela = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jBCancelar = new javax.swing.JButton();
        jBExcluir = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jBReset = new javax.swing.JButton();
        jBSalvar = new javax.swing.JButton();
        jBEditar = new javax.swing.JButton();
        jBAtualizar = new javax.swing.JButton();
        jBNovo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLTotal = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLAtivos = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro Login"));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Help/img/LATERAL.png"))); // NOI18N

        jTTabela.setModel(tmTabela);
        jScrollTabela = new javax.swing.JScrollPane();
        jTTabela.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        lsmTabela = jTTabela.getSelectionModel();
        lsmTabela.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    jTTabelaLinhaSelecionada(jTTabela);
                }
            }
        });
        jScrollTabela.setViewportView(jTTabela);

        jBCancelar.setText("SAIR");
        jBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelarActionPerformed(evt);
            }
        });

        jBExcluir.setText("Excluir");
        jBExcluir.setEnabled(false);
        jBExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBExcluirActionPerformed(evt);
            }
        });

        jComboBox1.setModel(tmCombo);
        jComboBox1.setEnabled(false);

        jLabel3.setText("Perfil de Acesso");

        jTextField1.setEnabled(false);

        jLabel1.setText("Login:");

        jBReset.setText("Resetar Senha");
        jBReset.setEnabled(false);
        jBReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBResetActionPerformed(evt);
            }
        });

        jBSalvar.setText("Salvar");
        jBSalvar.setEnabled(false);
        jBSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalvarActionPerformed(evt);
            }
        });

        jBEditar.setText("Editar");
        jBEditar.setEnabled(false);
        jBEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBEditarActionPerformed(evt);
            }
        });

        jBAtualizar.setText("Atualizar");
        jBAtualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAtualizarActionPerformed(evt);
            }
        });

        jBNovo.setText("Novo");
        jBNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBNovoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jBExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addComponent(jBNovo)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jBSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jBReset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jBEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jBAtualizar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jComboBox1, jTextField1});

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBCancelar, jBExcluir, jBNovo, jBSalvar});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jBReset)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBSalvar)
                    .addComponent(jBNovo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBExcluir)
                    .addComponent(jBCancelar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBAtualizar)
                .addContainerGap())
        );

        jLabel2.setText("Total:");

        jLabel6.setText("Ativos:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLTotal)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLAtivos))
                    .addComponent(jScrollTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jLAtivos)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLTotal))))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel4, jScrollTabela});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBExcluirActionPerformed
        // TODO add your handling code here:
        Excluir();
    }//GEN-LAST:event_jBExcluirActionPerformed

    private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed
        // TODO add your handling code here:
        if (t == null) {
            t = new Principal();
        }
        t.UserClose();
        dispose();
    }//GEN-LAST:event_jBCancelarActionPerformed

    private void jBEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEditarActionPerformed
        // TODO add your handling code here:
        Editar();
    }//GEN-LAST:event_jBEditarActionPerformed

    private void jBSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalvarActionPerformed
        // TODO add your handling code here:
        Cadastra();
    }//GEN-LAST:event_jBSalvarActionPerformed

    private void jBResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBResetActionPerformed
        // TODO add your handling code here:
        LimpaSenha();
    }//GEN-LAST:event_jBResetActionPerformed

    private void jBAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAtualizarActionPerformed
        // TODO add your handling code here:
        Atualizar();
    }//GEN-LAST:event_jBAtualizarActionPerformed

    private void jBNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBNovoActionPerformed
        novo(true);
        
    }//GEN-LAST:event_jBNovoActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBAtualizar;
    private javax.swing.JButton jBCancelar;
    private javax.swing.JButton jBEditar;
    private javax.swing.JButton jBExcluir;
    private javax.swing.JButton jBNovo;
    private javax.swing.JButton jBReset;
    private javax.swing.JButton jBSalvar;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLAtivos;
    private javax.swing.JLabel jLTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollTabela;
    private javax.swing.JTable jTTabela;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
    //variaveis inicio
    private List<Login> list;
    private DefaultTableModel tmTabela = new DefaultTableModel(null, new String[]{"NOME"});
    private DefaultComboBoxModel tmCombo = new DefaultComboBoxModel();
    private ListSelectionModel lsmTabela;
    PerfilControle p = new PerfilControle();
    List<PerfilAcesso> list1 = p.getList(new PerfilAcesso(), false);
    private boolean display = false;
    private boolean botoes = false;
    private boolean novo = false;
    //variaveis fim

    //botoes incio
    private void Cadastra() {
        Login l = new Login();
        l.setNome(jTextField1.getText());
        l.setSenha("");
        l.setPerfil(jComboBox1.getSelectedIndex());
        LoginControle ctrl = new LoginControle();
        ctrl.Adicionar(l);
        informacao("Adicionado");
        Atualizar();
    }
    
    private void novo(boolean novo) {
        // TODO add your handling code here:
        jTextField1.setText("");
        jComboBox1.setSelectedIndex(0);
        this.novo = novo;
        estadosBotoes();
    }
    
    private void Atualizar() {
        novo = false;
        botoes = false;
        display = false;
        estadosBotoes();
        listarTabela();
        novo(novo);
    }

    private void Excluir() {
        Login l = new Login();
        l.setId(list.get(jTTabela.getSelectedRow()).getId());
        LoginControle ctrl = new LoginControle();
        ctrl.Deletar(l);
        informacao("Deletado");
        Atualizar();
    }

    private void LimpaSenha() {
        Login l = new Login(
                list.get(jTTabela.getSelectedRow()).getId(),
                list.get(jTTabela.getSelectedRow()).getNome(),
                "",
                list.get(jTTabela.getSelectedRow()).getPerfil());

        LoginControle ctrl = new LoginControle();
        ctrl.Editar(l);
        informacao("Senha Zerada");
        Atualizar();
    }

    private void Editar() {
        Login l = new Login();
        l.setId(list.get(jTTabela.getSelectedRow()).getId());
        l.setNome(jTextField1.getText());
        l.setSenha(list.get(jTTabela.getSelectedRow()).getSenha());

        for (int i = 0; i < list1.size(); i++) {
            if (jComboBox1.getSelectedItem().equals(list1.get(i).getNome())) {
                l.setPerfil(list1.get(i).getId());
            }
        }

        LoginControle ctrl = new LoginControle();
        ctrl.Editar(l);
        informacao("Login Editado");
        Atualizar();
    }
    //botoes fim

    
    private void estadosBotoes() {
        //novo cadastro
        jBNovo.setEnabled(!novo);
        jBSalvar.setEnabled(novo);

        //botoes
        if (novo) {
            botoes = false;
        }
        jBEditar.setEnabled(botoes);
        jBExcluir.setEnabled(botoes);
        jBReset.setEnabled(botoes);
        //display
        if (novo || botoes) {
            display = true;
        } else {
            display = false;
        }

        jTextField1.setEnabled(display);
        jComboBox1.setEnabled(display);
    }

    private void iniciarComponentes() {
        System.out.println("Iniciar Cadastro de Login");
        listarCombo();
        listarTabela();
    }

    public void listarCombo() {
        tmCombo.addElement(null);
        for (int i = 0; i < list1.size(); i++) {
            tmCombo.addElement(list1.get(i).getNome());
        }
    }

    public void listarTabela() {
        LoginControle c = new LoginControle();
        list = c.getList(new Login(), false);
        mostrarTabela();
    }

    private void mostrarTabela() {
        while (tmTabela.getRowCount() > 0) {
            tmTabela.removeRow(0);
        }
        if (list.isEmpty()) {
            //se a lista for vazia
        } else {
            String[] linha = new String[]{null};
            int despensa = 0;
            for (int i = 0; i < list.size(); i++) {
                tmTabela.addRow(linha);
                tmTabela.setValueAt(list.get(i).getNome(), i, 0);
                if (list.get(i).getNome().contains("ZZ")) {
                    despensa++;
                }
            }
            jLTotal.setText(String.valueOf(list.size()));
            jLAtivos.setText(String.valueOf(list.size() - despensa));
        }
    }

    public void jTTabelaLinhaSelecionada(JTable jTTabela) {
        if (jTTabela.getSelectedRow() != -1) {
            this.botoes = true;
            jTextField1.setText(list.get(jTTabela.getSelectedRow()).getNome());
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list1.size(); j++) {
                    if(list.get(jTTabela.getSelectedRow()).getPerfil() == list1.get(j).getId()){
                        jComboBox1.setSelectedItem(list1.get(j).getNome());
                    }
                }
            }
        }else{
            botoes = false;
        }
        estadosBotoes();
    }

    private void informacao(String informacao) throws HeadlessException {
        JOptionPane.showMessageDialog(null, informacao + " com sucesso!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
        Atualizar();
    }

    
}
